import Vue from 'vue'
import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['Login'] // no redirect whitelist
const self = Vue.prototype;
router.beforeEach((to, from, next) => {
    NProgress.start() // start progress bar
    if(to.meta.title){
        document.title = to.meta.title
    }
    if (whiteList.includes(to.name)) {
        next()
    }else{
        if (store.state.permission.length === 0 || store.state.userRouters.length === 0) {
            self.$http.post(self.api.getUserInfo).then(res => {
                if(res.code != 0){
                    return
                }
                store.dispatch('setUserInfo',res).then(() => {
                    //增加路由
                    store.dispatch('generateRoutes').then(() => {
                        router.addRoutes(store.state.userRouters)
                        const redirect = decodeURIComponent(from.query.redirect || to.path)
                        if (to.path === redirect) {
                            if(to.path === '/'){
                                next({path:store.getters.getUserGoRouter.path})
                            }else{
                            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                                next({ ...to, replace: true })
                            }
                        } else {
                            // 跳转到目的路由
                            next({ path: redirect })
                        }
                    })
                })
            }).catch(err => {
                console.log(err)
            })
        } else {
            //获取用户的有权限访问的
            if (to.path === '/system/login') {
                next({path:store.getters.getUserGoRouter.path})
                NProgress.done()
            }else{
                next()
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done() // finish progress bar
})
